<!--
文件名: src/views/device/list/index.vue
功能: 设备列表管理页 (CRUD)
描述: 包含筛选、分页、新增、编辑、删除、图片预览等功能。(已修复Bug)
-->
<template>
  <div class="app-container">
    <!-- 1. 筛选与搜索区 -->
    <el-card shadow="never">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="query-form">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="设备分类" prop="category_id">
          <el-select v-model="queryParams.category_id" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 数据表格与操作区 -->
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <el-button type="success" :icon="Plus" @click="handleCreate">新增设备</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="deviceList">
        <el-table-column label="ID" prop="id" width="120" align="center" />
        <el-table-column label="图片" width="120" align="center">
          <template #default="scope">
            <el-image
              :src="getFullImageUrl(scope.row.image_url)"
              :preview-src-list="[getFullImageUrl(scope.row.image_url)]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="设备名称"
          prop="name"
          width="240"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备型号"
          prop="model"
          width="240"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="分类" prop="category.name" width="180" align="center" />
        <el-table-column label="费率(元/时)" prop="hourly_rate" align="center" width="120" />
        <el-table-column label="可预约" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_reservable ? 'success' : 'danger'">
              {{ scope.row.is_reservable ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="getList"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 3. 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogCancel"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备分类" prop="category_id">
          <el-select v-model="form.category_id" placeholder="请选择分类">
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备图片" prop="image_url">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <!-- 【修复点4】上传组件的预览图也使用辅助函数 -->
            <img v-if="form.image_url" :src="getFullImageUrl(form.image_url)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="费率(元/时)" prop="hourly_rate">
          <el-input-number v-model="form.hourly_rate" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="是否可预约" prop="is_reservable">
          <el-switch v-model="form.is_reservable" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadProps } from 'element-plus'
import {
  getDeviceListApi,
  createDeviceApi,
  updateDeviceApi,
  deleteDeviceApi,
  getAllDeviceCategoriesApi,
} from '@/api'
import type {
  Device,
  DeviceListParams,
  DeviceCreate,
  DeviceUpdate,
  DeviceCategory,
} from '@/api/types/device'
import { Search, Refresh, Plus, Edit, Delete, Picture } from '@element-plus/icons-vue'

// --- 辅助函数 ---
// 【修复点1】新增一个辅助函数来处理图片的URL
const getFullImageUrl = (relativeUrl: string | null | undefined) => {
  if (!relativeUrl) {
    return '' // or a path to a default placeholder image if you have one
  }
  // 使用 Vite 的环境变量来获取后端的基地址
  return `${import.meta.env.VITE_API_BASE_URL}${relativeUrl}`
}

// --- 响应式状态定义 ---
const loading = ref(true)
const total = ref(0)
const deviceList = ref<Device[]>([])
const categoryOptions = ref<DeviceCategory[]>([])

// --- 表单与对话框 ---
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const form = reactive<DeviceCreate>({
  name: '',
  category_id: undefined,
  model: '',
  remarks: '',
  is_reservable: true,
  hourly_rate: 0,
  image_url: '',
})
const rules = reactive({
  name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  category_id: [{ required: true, message: '设备分类必须选择', trigger: 'change' }],
})
const currentDeviceId = ref<number | null>(null)

// --- 查询参数 ---
const queryFormRef = ref<FormInstance>()
const queryParams = reactive<DeviceListParams>({
  page: 1,
  size: 6, // 【修复点5】将默认页面大小从10改为6
  name: undefined,
  category_id: undefined,
})

// --- 图片上传 ---
const uploadUrl = `${import.meta.env.VITE_API_BASE_URL}/api/admin/uploads/equipment_image`
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('admin-token')}`,
}

// --- API调用与逻辑处理 ---
const getList = async () => {
  loading.value = true
  try {
    const response = await getDeviceListApi(queryParams)
    deviceList.value = response.items
    total.value = response.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const getCategories = async () => {
  try {
    categoryOptions.value = await getAllDeviceCategoriesApi()
  } catch (error) {
    console.error(error)
  }
}

const handleQuery = () => {
  queryParams.page = 1
  getList()
}

const handleReset = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleCreate = () => {
  dialogTitle.value = '新增设备'
  dialogVisible.value = true
}

const handleEdit = (row: Device) => {
  currentDeviceId.value = row.id
  Object.assign(form, {
    name: row.name,
    category_id: row.category.id,
    model: row.model,
    remarks: row.remarks,
    is_reservable: row.is_reservable,
    hourly_rate: Number(row.hourly_rate),
    image_url: row.image_url,
  })
  dialogTitle.value = '编辑设备'
  dialogVisible.value = true
}

const handleDelete = async (row: Device) => {
  try {
    await ElMessageBox.confirm(`确认要删除设备 [${row.name}] 吗？`, '警告', {
      type: 'warning',
    })
    await deleteDeviceApi(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') console.error(error)
  }
}

const handleDialogCancel = () => {
  dialogVisible.value = false
  currentDeviceId.value = null
  formRef.value?.resetFields()
  form.image_url = ''
}

const handleSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (currentDeviceId.value) {
          await updateDeviceApi(currentDeviceId.value, form as DeviceUpdate)
          ElMessage.success('更新成功')
        } else {
          await createDeviceApi(form)
          ElMessage.success('新增成功')
        }
        handleDialogCancel()
        getList()
      } catch (error) {
        console.error(error)
      }
    }
  })
}

const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  form.image_url = response.url
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isImg = ['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isImg) ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!')
  if (!isLt2M) ElMessage.error('上传图片大小不能超过 2MB!')

  return isImg && isLt2M
}

// --- 生命周期钩子 ---
onMounted(() => {
  getList()
  getCategories()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/* 【修复点6】为筛选区的 el-select 添加最小宽度 */
.query-form .el-select {
  min-width: 180px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

/* el-upload 样式 */
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
